package cn.zhoutingrui.pethome.system.logininfo.service.impl;

import cn.zhoutingrui.pethome.base.constants.BaseConstants;
import cn.zhoutingrui.pethome.config.BussnisEptional;
import cn.zhoutingrui.pethome.payload.PayloadData;
import cn.zhoutingrui.pethome.system.emp.domain.Employee;
import cn.zhoutingrui.pethome.system.emp.domain.EmployeeBo;
import cn.zhoutingrui.pethome.system.emp.mapper.EmployeeMapper;
import cn.zhoutingrui.pethome.system.logininfo.domain.Logininfo;
import cn.zhoutingrui.pethome.system.logininfo.mapper.LogininfoMapper;
import cn.zhoutingrui.pethome.system.logininfo.service.ILogininfoService;
import cn.zhoutingrui.pethome.base.service.impl.BaseServiceImpl;
import cn.zhoutingrui.pethome.system.permission.mapper.PermissionMapper;
import cn.zhoutingrui.pethome.system.role.mapper.RoleMapper;
import cn.zhoutingrui.pethome.system.user.domain.User;
import cn.zhoutingrui.pethome.system.user.domain.UserBo;
import cn.zhoutingrui.pethome.system.user.domain.Wxuser;
import cn.zhoutingrui.pethome.system.user.mapper.UserMapper;
import cn.zhoutingrui.pethome.system.user.mapper.WxuserMapper;
import cn.zhoutingrui.pethome.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.util.LRUCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-01-28
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private getWechatUrl getWechatUrl;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Value("${Jwt.privateKey}")
    private String privateKeystr;
    @Value("${Jwt.publicKey}")
    private String publicKeystr;

    @Override
    public AjaxResultUtil findToLogin(Logininfo logininfo) {
        try {
            if (logininfo.getType()==null){
                throw new BussnisEptional("非法访问");
            }
            Logininfo emp = logininfoMapper.findToLogin(logininfo);
            if (emp==null){
                throw new BussnisEptional("用户名不存在");
            }
            //是否自动登录
            if (!logininfo.getAutoLogin()){
                String salt = emp.getSalt();
                String md5 = MD5Utils.encrypByMd5(logininfo.getPassword() + salt);
                if (!md5.equals(emp.getPassword())){
                    throw new BussnisEptional("用户名或密码错误");
                }
            }
            //用户账号校验通过
            //获取私钥
            //System.out.println(privateKey);
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(privateKeystr).getFile());
            //获取存放载荷的对象
            PayloadData payloadData = new PayloadData();
            //判断当前登录人的类型
            if (emp.getType()==BaseConstants.Type.STATE_MANAGER){//员工类型
                EmployeeBo employeeBo = new EmployeeBo();
                BeanUtils.copyProperties(emp,employeeBo);
                //查询当前员工id
                Employee byLogininfoId = employeeMapper.findByLogininfoId(emp.getId());
                employeeBo.setId(byLogininfoId.getId());
                //员工信息存放到载荷中
                payloadData.setAdmin(employeeBo);
                //查询当前员工的角色id
                Long roleId = employeeMapper.findRoleByEmp(byLogininfoId.getId());
                if (roleId!=null){//有角色信息
                    //查询该员工的权限信息
                    List<Long> permissionIds = roleMapper.findByRole(roleId);
                    List<String> sns = permissionMapper.findSnById(permissionIds);
                    //把权限存入载荷
                    payloadData.setSns(sns);

                }
            }else {//用户类型
                UserBo userBo = new UserBo();
                BeanUtils.copyProperties(emp,userBo);
                //查询当前用户id
                User byLogininfoIdUser = userMapper.findByLogininfoIdUser(emp.getId());
                userBo.setId(byLogininfoIdUser.getId());
                //员工信息存放到载荷中
                payloadData.setUser(userBo);
            }


            //获取token
            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 300);
        /*String token = StrUtils.getRandomString(128);
        //存入redis,设置过期时间
        redisTemplate.opsForValue().set(token,emp, 30, TimeUnit.MINUTES);*/
            HashMap<String, Object> h = new HashMap<>();
            h.put("token",token);
            h.put("user",payloadData.getUser());
            h.put("admin",payloadData.getAdmin());
            h.put("logininfo",emp);
            h.put("sns",payloadData.getSns());
            return AjaxResultUtil.success().setData(h).setMsg("userLogin");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //微信登录
    @Override
    public AjaxResultUtil wechatLogin(String code) {
        //获取asstoken的地址
        String accessToeknUrl = getWechatUrl.getAccessToekn(code);
        //向微信发送请求获取accesstoken
        String s = HttpClientUtils.httpGet(accessToeknUrl);
        //将结果转化为json
        JSONObject jsonObject = JSONObject.parseObject(s);
        //获取数据
        String accessToken = jsonObject.getString("access_token");
        String unionid = jsonObject.getString("unionid");
        String openid = jsonObject.getString("openid");
        //查询unionid是否存在
        Wxuser wxuser = wxuserMapper.findByUnionid(unionid);
        if (wxuser!=null){//用户使用过微信登录
            Long userId = wxuser.getUserId();
            if (userId!=null){//用户绑定了我们的账号
                //获取用户的登录信息
                User user = userMapper.findById(userId);
                Logininfo logininfo = new Logininfo();
                BeanUtils.copyProperties(user,logininfo);
                logininfo.setType(BaseConstants.Type.STATE_USER);
                logininfo.setAutoLogin(true);
                //调用登录接口,执行登录
                return findToLogin(logininfo);
            }else {//使用过微信登录,但未绑定账号
                return AjaxResultUtil.success().setMsg("bind").setData(unionid);
            }
        }else {//未使用过微信登录
            //向微信发送请求获取用户数据
            String userInfo = getWechatUrl.getUserInfo(accessToken, openid);
            String s1 = HttpClientUtils.httpGet(userInfo);
            Wxuser wxuserInfo = JSONObject.parseObject(s1, Wxuser.class);
            //添加数据
            wxuserMapper.add(wxuserInfo);
            return AjaxResultUtil.success().setMsg("bind").setData(wxuserInfo.getUnionid());
        }
    }
}
